package com.ruoci.redis.cacheavalanche;

import com.ruoci.redis.constants.BusinessConstants;
import com.ruoci.redis.response.BasicResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @Author yang
 * 缓存雪崩(Redis 中大量 key 失效，导致大量请求访问数据库)
 **/
@Slf4j
@RestController
@RequestMapping("/avalanche")
public class AvalancheController {

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("/cache")
    public BasicResponse breakdown(){
        Duration expire = Duration.ofHours(2L).plus(Duration.ofSeconds((int) (Math.random())));
        redisTemplate.opsForValue().set(BusinessConstants.RANDOM_KEY,BusinessConstants.RANDOM_KEY, expire);
        return BasicResponse.success();
    }
}
